/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */
package com.flavienlaurent.discrollview.lib;

import ohos.agp.colors.HsvColor;

/**
 * HsvEvaluator
 *
 * @since 2021-03-01
 */
public class HsvEvaluator {
    private static final int THREE = 3;
    private static final int TWO = 2;
    private static final int ONEEIGHTZERO = 180;
    private static final int THREESIXZERO = 360;
    private static final int TWOFOUR = 24;
    float[] startHsv = new float[THREE];
    float[] endHsv = new float[THREE];
    float[] outHsv = new float[THREE];

    /**
     * evaluate
     *
     * @param fraction
     * @param startValue
     * @param endValue
     * @return Integer
     */
    public Integer evaluate(float fraction, Integer startValue, Integer endValue) {
        startHsv[0] = HsvColor.toHSV(startValue).getHue();
        startHsv[1] = HsvColor.toHSV(startValue).getSaturation();
        startHsv[TWO] = HsvColor.toHSV(startValue).getValue();
        endHsv[0] = HsvColor.toHSV(endValue).getHue();
        endHsv[1] = HsvColor.toHSV(endValue).getSaturation();
        endHsv[TWO] = HsvColor.toHSV(endValue).getValue();

        // 计算当前动画完成度（fraction）所对应的颜色值

        if (endHsv[0] - startHsv[0] > ONEEIGHTZERO) {
            endHsv[0] -= THREESIXZERO;
        } else if (endHsv[0] - startHsv[0] < -ONEEIGHTZERO) {
            endHsv[0] += THREESIXZERO;
        }
        outHsv[0] = startHsv[0] + (endHsv[0] - startHsv[0]) * fraction;
        if (outHsv[0] > THREESIXZERO) {
            outHsv[0] -= THREESIXZERO;
        } else if (outHsv[0] < 0) {
            outHsv[0] += THREESIXZERO;
        }
        outHsv[1] = startHsv[1] + (endHsv[1] - startHsv[1]) * fraction;
        outHsv[TWO] = startHsv[TWO] + (endHsv[TWO] - startHsv[TWO]) * fraction;
        int alpha = startValue >> TWOFOUR
            + (int) ((endValue >> TWOFOUR - startValue >> TWOFOUR) * fraction); // 计算当前动画完成度（fraction）所对应的透明度
        return HsvColor.toColor(alpha,outHsv[0],outHsv[1],outHsv[TWO]); // 把 HSV 转换回 ARGB 返回
    }
}
